/**
 * Created by 준영 on 2014-05-12.
 */

var async = require('async');
var util = require("util");
var ObjectID = require ('mongodb').ObjectID;

var BaseApi = require('./baseApi').BaseApi;

exports.FreeboardApi = (function() {
    function FreeboardApi(mongoDB, keyValueStore, sessionStore) {
        this.mongoDB = mongoDB;
        this.keyValueStore = keyValueStore;
        this.sessionStore = sessionStore;
    }

    util.inherits(FreeboardApi, BaseApi);

    FreeboardApi.method("deleteFreeboardItem", function(req, res)
    {

        var data = req.body;
        this.mongoDB.db.collection(data.boardType).remove({_id: ObjectID(req.body._id)}, function (err, result)
        {
            if(err == null) {
                res.send("ok");
            }
            else
            {
                res.send("fail");
            }
        });
    });

    FreeboardApi.method('modifyFreeboardItem', function(req, res)
    {

        var data = req.body;
        var deleteImageCollection  = req.body.deleteImages.map(function(item)
        {
            return {name:item}}
        );
        this.mongoDB.db.collection(data.boardType).update({_id: ObjectID(data._id)},
           {$set:{subject: req.body.subject, body: req.body.body  }},
            {$pull: {images: [deleteImageCollection ]}},
            function (err, result) {
                if(err == null)
                {
                    res.send("ok");
                }
                else
                {
                    res.send("fail");
                }
            });
    });
    //게시판 글쓰기
    FreeboardApi.method("writeFreeboard", function(req, res)
    {
        var _self = this;
        req.body.last_update = new Date();
        req.body.readCount = 0;

        if(typeof req.body.images !== "undefined")
        {
            req.body.images.forEach(function(item)
            {

                item.name = item.token + item.name;
            });
        }
        _self.mongoDB.db.collection('users').findOne({"id":req.body.userID },function(findOneError, findOneResult)
        {
            if(findOneError == null) {
                req.body.nickname = findOneResult.nickname;
                _self.mongoDB.db.collection(req.body.boardType).insert(req.body, function (err, result) {
                    res.send("ok");
                });
            }
        });

    });

    FreeboardApi.method("getTotalCount", function(req, res)
    {
        var data = req.query;

        this.mongoDB.db.collection(data.boardType).count(
            {$or: [
                { "subject": new RegExp(data.searchText)},
                {"body": new RegExp(data.searchText)}
            ]}, function (err, result) {
                res.send({'totalCount': result});
            });
    });

    FreeboardApi.method('createComment', function(req, res)
    {
        /*  var data = req.query;
         this.mongoDB.db.collection('freeboard')

         */

        this.mongoDB.db.collection(req.body.boardType).update({_id: ObjectID(req.body._id)},{
            $push: {
                comments: {
                    "commentID": req.session.user,
                    "commentContent": req.body.commentContent,
                    "last_update": new Date()
                }
            }
        },function(err,res){

        });

    });
    //게시판 리스트 불러오기
    FreeboardApi.method("getFreeboardList", function(req, res)
    {


        var data = req.query;
        //    this.mongoDB.db.collection('freeboard').find().skip(Number(data.index)).limit(Number(data.limit)).toArray(function(err, result)
        this.mongoDB.db.collection(data.boardType).find(
            {"subject" : new RegExp(data.searchText)}
        ).sort({_id: -1}).skip(Number(data.index)).limit(Number(data.limit)).toArray(function(err, result)
            {

                /*     result.forEach(function(item)
                 {
                 item.last_update =  dateFormat( item.last_update , 'mm-dd HH:mm');
                 });*/
                //var string = result[0]._id.toHexString();
                /* var cursor = this.db.collection('approval').find({
                 $and:[
                 {$or: statusesCondition},
                 {$or: emailCondition}
                 ]}
                 );

                 cursor.count(function(err, count){
                 cursor
                 .sort(sort)
                 .skip(skip)
                 .limit(limit)
                 .toArray(function(err, list){
                 callback(err, {list:list || [], totalCount:count || 0});
                 });
                 });*/
                res.send(result);
            });
    });

    FreeboardApi.method("getPrevAndNextItemIndex", function(req, res)
    {
        var self = this;

        var data = req.query;
        var prevItem = {};
        var nextItem = {};
        var currentItem ={};
        async.waterfall([
                function(callback) {
                    self.mongoDB.db.collection(data.boardType).findOne({"_id": { $lt: ObjectID(data._id)}},{sort: {_id: -1}}, function (err, result) {
                        if(err != null)
                        {
                            console.log(err.message);
                        }
                        prevItem = result;
                        callback(null);
                    });
                },
                function(callback) {
                    self.mongoDB.db.collection(data.boardType).findOne({"_id": { $gt: ObjectID(data._id)}}, function (err, result) {
                        if(err != null)
                        {
                            console.log(err.message);
                        }
                        nextItem = result;

                        callback(null);
                    });
                },
                function(callback){
                    self.mongoDB.db.collection(data.boardType).findOne({"_id":  ObjectID(data._id)}, function (err, result) {
                        if(err != null)
                        {
                            console.log(err.message);
                        }
                        currentItem = result;

                        self.mongoDB.db.collection(data.boardType).update({_id: ObjectID(data._id)},{
                            $inc: {readCount : 1}

                        },function(err,res){

                        });
                        callback(null);
                    });
                }],
            function(err){
                if(err != null) {
                    console.log(err.message);
                }
                res.send({prevItem : prevItem,nextItem : nextItem, currentItem: currentItem});
            });



    });
    return FreeboardApi;
})();
